#coding:utf-8
import re
import json
import urllib
import urllib2
import cookielib
import codecs
import httplib

class JString(object):
    def __init__(self):
        self.str = '['
    def add(self,one):
        one = dict(one)
        s = json.dumps(one, ensure_ascii=False)
        if self.str == '[':
            self.str += s
        else:
            self.str += ','+s
    def get(self):
        return self.str + ']'
    def __str__(self):
        return self.str + ']'

class Opener:
    cookie = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
    def login(self,u,data):
        postdata=urllib.urlencode(data)
        req = urllib2.Request(
            url = u,
            data = postdata
        )
        result = self.opener.open(req)
        return result.read()
    def show_cookie(self):
        for item in self.cookie:
            print 'Cookie：Name = '+item.name
            print 'Cookie：Value = '+item.value
    def openurl(self,url):
        try:
            result = self.opener.open(url)
        except urllib2.URLError:
            print("urlError:",url)
            return ''
        except urllib2.HTTPError:
            print("httpError:",url)
            return ''
        try:
            return result.read()
        except httplib.IncompleteRead:
            print('incompleteRead',url)
            return ''
    def save(self,file,what):
        file = codecs.open(file, 'w', encoding='utf-8')
        file.write(what)
        file.close()


def main():
    a = Opener()
    res = a.login('http://202.115.47.141/loginAction.do',{'zjh':'2012141461255','mm':'078913'})
    m = re.search(r'frameset',res)
    if m:
        res = a.openurl('http://202.115.47.141/xkAction.do?actionType=6')

if __name__=='__main__':
    # main()
    pass
